//
//  StoreTableViewController.m
//  BestPriceApp
//
//  Created by You50029 on 2014-03-28.
//  Copyright (c) 2014 AresSystems. All rights reserved.
//

#import "StoreTableViewController.h"
#import "StoreViewCell.h"
#import "Store.h"

#define phpLinkProduct @"http://www.bestprice.ma/api/products/?t="
#define phpLinkStore   @"http://www.bestprice.ma/api/stores/"

@interface StoreTableViewController ()

@end

@implementation StoreTableViewController

@synthesize searchString, stores, label;

- (IBAction) CloseButtonTapped
{
    [self dismissModalViewControllerAnimated:YES];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *webserviceProduct = [phpLinkProduct stringByAppendingString:searchString];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:webserviceProduct]];
        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];
        
    });
    
}

- (void)fetchedData:(NSData *)responseData {
    NSArray* json = [NSJSONSerialization
                     JSONObjectWithData:responseData //1
                     options:kNilOptions error:nil];
    
    NSSortDescriptor *nameSorter = [[NSSortDescriptor alloc] initWithKey:@"storeid" ascending:YES];
    NSSortDescriptor *priceSorter = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];
    
    json = [json sortedArrayUsingDescriptors:[NSArray arrayWithObjects:nameSorter,priceSorter,nil]];

    
    int counter = 0;
    NSMutableArray *json2 = [[NSMutableArray alloc] init];
    
    for (NSDictionary *dict in json) {
        
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
        
        [dictionary setObject:[dict objectForKey:@"storeid"] forKey:@"storeid"];
        [dictionary setObject:[dict objectForKey:@"label"] forKey:@"productLabel"];
        [dictionary setObject:[dict objectForKey:@"price"] forKey:@"productPrice"];
        [dictionary setObject:[dict objectForKey:@"picture"] forKey:@"productPicture"];
        
        NSString *storeid = [dict objectForKey:@"storeid"];
        
        NSString *webserviceStore = [phpLinkStore stringByAppendingString:storeid];
        webserviceStore = [webserviceStore stringByAppendingString:@"/"];
        
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:webserviceStore]];
            [self performSelectorOnMainThread:@selector(fetchedStore:)
                                   withObject:data waitUntilDone:YES];
            
        });
        
        [dictionary setObject:self.label.storeLabel forKey:@"storeLabel"];
        [dictionary setObject:self.label.storeUrl forKey:@"storeUrl"];
        
        [json2 addObject:dictionary];
        
        counter++;
        
    }
    self.stores = [json2 copy];

    [self.tableView reloadData];
    
    
}

- (void)fetchedStore:(NSData *)responseData {
    NSDictionary* json = [NSJSONSerialization
                         JSONObjectWithData:responseData //1
                         options:kNilOptions error:nil];

    self.label = [[ Store alloc] initWithJson:json];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [stores count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    StoreViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    cell.storeLabel.text   = [[stores objectAtIndex:indexPath.row] objectForKey:@"storeLabel"];
    cell.storeUrl.text     = [[stores objectAtIndex:indexPath.row] objectForKey:@"storeUrl"];
    cell.productLabel.text = [[stores objectAtIndex:indexPath.row] objectForKey:@"productLabel"];
    cell.productPrice.text = [[stores objectAtIndex:indexPath.row] objectForKey:@"productPrice"];
    cell.pictureUrl.text   = [[stores objectAtIndex:indexPath.row] objectForKey:@"productPicture"];
    
    NSString *imageurl = @" ";
    
    if ([cell.pictureUrl.text rangeOfString:@"http"].location == NSNotFound) {
     imageurl  = [cell.storeUrl.text stringByAppendingString:cell.pictureUrl.text];
    } else {
     imageurl  = cell.pictureUrl.text;
    }
    
    NSURL    *imageURL  = [NSURL URLWithString:imageurl];
    NSData   *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage  *image     = [UIImage imageWithData:imageData];
    
    cell.pictureUrl.text   = imageurl;
    
    cell.productLogo.image = image;
    
    return cell;
}



@end
